/*
 * @Autor: Ruohong Yu
 * @Date: 2023-04-01 12:42:48
 * @Description: file content
 * @FilePath: \ebookd:\program\vsc\ebook\node-ebook\router_handler\userinfo.js
 */
const config=require('../bin/const')
const db = config.db
const bcrypt = require('bcryptjs')
const cryptoaes = require('../utils/cryptoforaes')
// 头像上传模块
const uploadAvatar = require('../utils/multer/upload')

//记录邮箱验证码
let code={email:'',code:''}

function randomWord(randomFlag, min, max){
  var str = "",
      range = min,
      arr = ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z', 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z'];

  // 随机产生
  if(randomFlag){
      range = Math.round(Math.random() * (max-min)) + min;
  }
  for(var i=0; i<range; i++){
      pos = Math.round(Math.random() * (arr.length-1));
      str += arr[pos];
  }
  return str;
}

function sendEmail(data,touser){
  let options = {
    from: ' "Ybook Reader" <1321415061@qq.com>',
    to: '<'+touser+'>',
    bcc: '密送',
    subject: 'Ybook Reader验证码邮件',
    text: data,
    html: '<h1>From Ybook Reader</h1><h2>您的验证码为: '+data+ '</h2><h1>验证码有效期为5分钟</h1>'
  };
  config.mailTransport.sendMail(options,function(err,msg) {
    if(err) {
        console.log(err);
        return false
    } else {
        return true
    }
  })
}

//发送邮箱验证码
exports.sendEmailCode=(req,res)=>{
  code.email=req.body.email
  code.code=randomWord(true, 4,6)
  setTimeout(() => {
    delete code
  }, 300000)
  try{
    sendEmail(code.code,req.body.email)
    res.send({ status: 0, message: '发送验证码成功' })
  }catch(err){
    res.send({ status: 1, message: '发送验证码失败' })
  }
}


// 更新用户基本信息
exports.updateUserInfo = (req, res) => {
  let userinfo=req.body
  const sql = `select * from users where username=?`
  db.query(sql, userinfo.username, (err, results) => {
    if (err) return res.send({ status: 1, message: err.message })
    if (results.length === 1 && userinfo.username!==userinfo.reusername) return res.send({ status: 2, message: '该用户名已存在' })
    const sql = `update users set username=?,email=? where username=?`
    db.query(sql, [userinfo.username, userinfo.email, userinfo.reusername], (err, results) => {
      if (err) return res.send({ status: 1, message: err.message })
      if (results.affectedRows !== 1) return res.send({ status: 1, message: '更新用户的基本信息失败！' })
      res.send({
        status: 0,
        message: '更新用户信息成功！'
      })
    })
  })
}

// 更新用户密码
exports.updatePassword = (req, res) => {
  const sql = `select * from users where email=?`
  db.query(sql, req.body.email, (err, results) => {
    if (err) return res.send({ status: 1, message: err.message })
    if (results.length !== 1) return res.send({ status: 3, message: '用户不存在！' })
    if(req.body.emailcode===code.code&&req.body.email===code.email){
      const sql2 = `update users set password=? where email=?`
      let cryptopwd=cryptoaes.decrypt(req.body.password)
      const newPwd = bcrypt.hashSync(cryptopwd, 10)
      db.query(sql2, [newPwd, req.body.email], (err, results) => {
        if (err) return res.send({ status: 1, message: err.message })
        if (results.affectedRows !== 1) return res.send({ status: 1, message: '更新密码失败！' })
        res.send({ status: 0, message: '更新密码成功！' })
      })
    }else{
      res.send({ status: 2, message: '验证码不正确' })
    }
  })
}

// 更新用户头像
exports.updateAvatar = async (req, res) => {
  try {
    const uploadRes = await uploadAvatar(req, res)
    let userinfo=req.body
    const sql = `update users set avatar=? where username=?`
    db.query(sql, [uploadRes.img_url,userinfo.username], (err, results) => {
      if (err) return res.send({ status: 1, message: err.message })
      res.send({ status: 0, message: '上传成功！', img_url: uploadRes })
    })
  } catch (err) {
    res.send({ status: 1, message: err.message })
  }
}
